﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Torch_IRepository;

namespace Torch_Repository
{
    /// <summary>
    ///岗位表
    /// </summary>
    public class JobDal : BaseDal<Job>, IJobsDal
    {
        private SmartSchoolDbContext _dbcontext;
        private IJobPermissionDal _ijobpermission;
        public JobDal(SmartSchoolDbContext dbcontext, IJobPermissionDal ijobpermission) : base(dbcontext)
        {
            _dbcontext = dbcontext;
            _ijobpermission = ijobpermission;
        }

        public override async Task<int> DeleteAsync(Job entity, bool isSaved = true) 
        {
            var result = 0;
            using (IDbContextTransaction _tran = _dbcontext.Database.BeginTransaction()) 
            {
                try
                {
                    _dbcontext.Entry(entity).State = EntityState.Deleted;
                    var data = await _ijobpermission.QueryAsync(jbp => jbp.Id == entity.Id);
                    var jobpSum = 0;
                    if (data != null) 
                    {
                        foreach (var i in data)
                        {
                            jobpSum += await _ijobpermission.DeleteAsync(i);
                        }
                    }
                    else
                    {
                        return result;
                    }

                    if (jobpSum == data.Count)
                    {
                        result = await _dbcontext.SaveChangesAsync();
                        if (result < 0)
                        {
                            _tran.Rollback();
                            result = 0;
                        }
                        else
                        {
                            _tran.Commit();
                        }
                    }
                    else
                    {
                        _tran.Rollback();
                    }

                }
                catch (Exception)
                {

                    _tran.Rollback();
                }
                
                return result;
            }
        }
    }
}
